import sys

sys.path.append('/usr/local/lib/python3.6/site-packages')
sys.path.append('/root/anaconda3/lib/python3.6/site-packages')
sys.path.append('../')

from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from pymongo import MongoClient
from selenium import webdriver

import platform
import pprint
import codecs
import time
import json
import re
import os
import sys

if sys.stdout.encoding != 'UTF-8':
    sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer, 'strict')
if sys.stderr.encoding != 'UTF-8':
    sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer, 'strict')

client18 = MongoClient('47.96.88.18', 27017, connect = False)

qushu_resume_db = client18['qushu_resume_db']
qushu_resume_coll = qushu_resume_db['qushu_resume_coll']

driver = None


def new_driver(headless = False):
    if 'Darwin' in platform.platform():
        options = webdriver.ChromeOptions()

        if headless:
            options.add_argument('--headless')
            options.add_argument('--disable-gpu')
            options.add_argument('--disable-images')

        desired_capabilities = options.to_capabilities()

        chrome_driver_path = '/Users/xuchaosheng/Workspace/cv_match/binary/chromedriver'
        driver = webdriver.Chrome(chrome_driver_path, desired_capabilities = desired_capabilities)
    else:
        from selenium.webdriver import FirefoxOptions

        opts = FirefoxOptions()
        opts.add_argument('--headless')
        driver = webdriver.Firefox(firefox_options = opts)

    return driver


def login(loginName, password):
    global driver

    driver = new_driver()
    driver.get('https://passport.zhaopin.com/org/login')

    driver.find_element_by_id('loginName').send_keys(loginName)
    driver.find_element_by_id('password').send_keys(password)
    time.sleep(1)
    driver.find_element_by_id('loginbutton').click()
    time.sleep(10)

    if driver.find_element_by_class_name('geetest_panel'):
        code_pic_src = driver.find_element_by_class_name('geetest_item_img').get_attribute('src')

        return {
            'code_pic_src': code_pic_src,
            'action': 'code'
        }

    # time.sleep(3)
    #
    # driver.find_element_by_class_name('login-wx').click()
    # wx_qr_code = driver.find_element_by_id('login-code').get_attribute('src')
    # time.sleep(20)
    #
    # return {
    #     'code_pic_src': wx_qr_code,
    #     'action': 'code'
    # }


def hit_code(positions):
    for pos in positions:
        ele = driver.find_element_by_class_name('geetest_item_img')
        actions = ActionChains(driver)
        actions.move_to_element_with_offset(ele, pos['offsetX'], pos['offsetY'])
        actions.click()
        actions.perform()
        time.sleep(2)

    # 打码确认
    driver.find_element_by_class_name('geetest_commit').click()
    time.sleep(3)
    driver.find_element_by_id('loginbutton').click()
    print('点击登录')

    # 登陆确认
    # for i in range(1000):
    #     try:
    #         driver.find_element_by_id('loginbutton').click()
    #         break
    #     except:
    #         continue

    time.sleep(50)


def search(q):
    driver = new_driver(headless = 0)
    driver.get('https://ihr.zhaopin.com/')

    with open(os.path.join(os.getcwd(), 'simulator', 'cookie_0.text'), 'r') as f:
        cookies = json.load(f)

        for item in cookies:
            try:
                driver.add_cookie(item)
            except:
                continue

    driver.get('https://rd5.zhaopin.com/custom/searchv2/result')
    time.sleep(2)

    if driver.find_element_by_css_selector('.searchv2-intro__show-overlay'):
        try:
            driver.find_element_by_css_selector('.searchv2-intro__show-helper img').click()
        except:
            pass

    time.sleep(1)

    # 清空搜索条件
    driver.find_element_by_css_selector('#resume-filter-form > div.resume-filter__pane > div > button:nth-child(2)').click()

    # 公司名称搜索
    if len(q['work_experience']):
        driver.find_element_by_css_selector('#form-item-9 > div > input').send_keys(' '.join([we['company'] for we in q['work_experience']]))

    # 院校搜索
    if len(q['edu_experience']):
        driver.find_element_by_css_selector('#form-item-41 > div > input').send_keys(q['edu_experience'][0]['school'])

    # 确认条件
    driver.find_element_by_css_selector('.resume-filter__grid .k-input__inner').send_keys(Keys.ENTER)

    time.sleep(2)

    main_window = driver.current_window_handle

    matched_url = ''

    for item__basic, item__extend in zip(driver.find_elements_by_css_selector('.search-list tbody tr.resume-item__basic'), driver.find_elements_by_css_selector('.search-list tbody tr.resume-item__extend')):
        info = {
            'rname': item__basic.find_element_by_css_selector('.is-text-normal').text.strip().replace('【已查看】', ''),
            'jname': item__basic.find_elements_by_css_selector('.is-text-tiny')[1].text.strip(),
            'sex': item__extend.find_element_by_css_selector('span[data-bind="text: gender"]').text.strip(),
            'phd': item__extend.find_element_by_css_selector('span[data-bind="text: eduLevel"]').text.strip(),
            'age': item__extend.find_element_by_css_selector("""span[data-bind="text: age? age + '岁' : ''"]""").text.strip().replace('岁', ''),
            'loc': item__extend.find_element_by_css_selector('span[data-bind="text: city"]').text.strip()
        }

        pprint.pprint(info)

        if info['age'] in q['info'].values() and info['loc'] in q['info'].values() and info['phd'] in q['info'].values():
            for i in range(100):
                try:
                    item__basic.find_element_by_css_selector('.is-text-normal').click()
                    break
                except:
                    driver.execute_script("window.scrollTo(0,window.scrollY + 200)")

            for h in driver.window_handles:
                if h != main_window:
                    driver.switch_to_window(h)
                    break

            matched_url = driver.current_url
            break

    driver.quit()
    return matched_url


if __name__ == '__main__':
    # for i in qushu_resume_coll.find({'platform': 'zhilian', 'wanted_job.title': re.compile('软件测试')}).limit(1):
    #     pprint.pprint(i)
    #     matched_url = search(i)
    #     print(matched_url)

    login('sousuozhanghao2', 'zhaopin123')
